In [15]:
%%writefile my_code.py
from time import sleep
def stupid_func(a):
"""
Stupid function that sleep for 0.01sec and return the parameter squared
Parameter
---------
a float
a number you want to square
Returns
-------
b float
b = a**2
Example
-------
>>> stupid_func(2.)
4.0
"""
sleep(0.01)
return a**2.
def run_100_times():
"""Runs that stupid_func 100 times"""
for i in range(100):
stupid_func(i)
if __name__ == "__main__":
run_100_times()
In [2]:
!python -m cProfile -s time my_code.py
Note that the cumulated time of the program should be 100*0.01 = 1.0 sec, because of the overhead of python (and especially the profiler) it's a bit longer.
Note that the function my_code.py:3(stupid_func)
is run 100 times.
In [13]:
import cProfile, pstats, StringIO
from my_code import run_100_times
pr = cProfile.Profile()
pr.enable()
run_100_times()
pr.disable()
s = StringIO.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('tottime')
ps.print_stats()
print s.getvalue()
You just need to use the magic line function %prun
or cell function %%prun
In [8]:
%prun run_100_times()
In [9]:
%%prun
for i in range(100):
stupid_func(i)
In [10]:
%prun %run my_code.py
In [ ]: